﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace BLL.ProCheck
{
    /// <summary>
    /// 仓库盘点业务逻辑处理层
    /// </summary>
   public class ProCheckBLL : SysFrameWork.PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        List<OperateModel> operList;
        OperateModel oper;
        CuDbHelper cu_helper;
        public ProCheckBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            cu_helper = new CuDbHelper();
        }
       /// <summary>
       /// 获取ERP盘点任务单
       /// </summary>
       /// <returns></returns>
        //public ReturnResult GetERPTask(string condition)
        public ReturnResult GetERPTask( string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select s.cCVCode code,s.cInvCode proCode,s.cPosition positionCode,w.cWhName wareName,");
                sb.Append("s.autoID erpId,s.iCVQuantity number,m.cWhCode wareCode,p.cInvName proName,po.cPosName positionName,");
                sb.Append("p.cInvStd spec,cFree1 color,cFree3 shangbiao,dCVDate from CheckVouchs s inner join ");
                sb.Append("CheckVouch m  on m.cCVCode=s.cCVCode and m.dveridate is null ");
                sb.Append(" inner join Inventory p on p.cInvCode=s.cInvCode");
                sb.Append(" inner join Warehouse w on w.cWhCode=m.cWhCode");
                sb.Append(" left join Position po on s.cPosition=po.cPosCode and po.cWhCode=w.cWhCode");
                sb.Append(" where 1=1 ");
                var json= JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        if(obj.Name.Equals("sDate") )
                        {
                            if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                            {
                                sb.Append(" convert(datetime,dCVDate, 20)" + " >='" + json["sDate"].ToString() + "' ");
                            }
                        }
                        else if(obj.Name.Equals("eDate"))
                        {
                            if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                            {//结束时间
                                sb.Append(" convert(datetime,dCVDate, 20)" + "<= '" + json["eDate"].ToString() + "' ");
                            }
                        }else
                            sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                    }
                }
                var table =cu_helper.getData(sb.ToString(),userLogin.UserInfo().baseCode);
                var list = cmd.TableToDictionary(table);
                sb.Clear();
                sb.Append("select * from pCh_CheckTask_info where status='pct-doing'");
                sb.Append(" and isdel=0");
                var taskTable = cmd.GetDataTable(sb.ToString());//获取所有当前未结束的盘点任务
                for (int i = 0; i < list.Count; i++)
                {
                    var dr = taskTable.Select("erpId='" + list[i]["erpId"] + "'");
                    if (dr.Length > 0)
                    {
                        list[i]["isColor"] = "1";
                    }
                    else
                    {
                        list[i]["isColor"] = "0";
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 创建盘点任务
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult CreateTask(string datas, string type)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var dList = JsonConvert.DeserializeObject<List<DbCheckTaskInfo>>(datas);

                #region 判断是否重复创建盘点任务
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pCh_CheckTask_info where status='pct-doing' ");
                sb.Append(" and isdel=0 and erpCode='" + dList[0].erpCode.ToString() + "' ");
                var taskTable = cmd.GetDataTable(sb.ToString());//获取同盘点单 所有未结束的盘点任务
                if (taskTable.Rows.Count > 0)
                {
                    var msg = "当前盘点单已创建任务：" + taskTable.Rows[0]["erpCode"];
                    rsl.Message = msg;
                    return rsl;
                }
                #endregion

                var position = ""; var pro = ""; var number = "0";
                var proNames = "";

                foreach (var obj in dList)
                {
                    if (obj.erpPositionCode != null && !position.Contains(obj.erpPositionCode))
                        position = position + obj.erpPositionCode + ",";
                    if (obj.erpProCode != null && !pro.Contains(obj.erpProCode))
                        pro = pro + obj.erpProCode + ",";

                    proNames += obj.proName + ",";
                    number = (double.Parse(number) + double.Parse(obj.erpNumber)).ToString();
                }

                #region 创建盘点任务
                DbCheckTaskInfo taskInfo = new DbCheckTaskInfo();
                taskInfo.status = "pct-doing";
                taskInfo.pchCode = Guid.NewGuid().ToString().Replace("-", "");
                taskInfo.isdel = 0;
                taskInfo.createtime = getNow();
                taskInfo.createuser = userLogin.UserInfo().userCode;
                taskInfo.baseCode = userLogin.UserInfo().baseCode;
                var venCode = CreateCodeInfo("V", "盘点编码", 3);
                taskInfo.venCode = venCode;
                taskInfo.chType = type;
                taskInfo.erpWareCode = dList[0].erpWareCode;
                taskInfo.erpCode = dList[0].erpCode;
                if(type== "pc-pospro")
                {
                    taskInfo.proName = proNames.TrimEnd(',');
                }
                taskInfo.erpNumber = number;
                taskInfo.erpPositionCode = position.TrimEnd(',');
                taskInfo.erpProCode = pro.TrimEnd(',');
                oper = new OperateModel();
                oper.Data = taskInfo;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        //创建盘点清单
                        //CreateTaskData(dList);
                        CreateTaskData(taskInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取ERP盘点任务单
        /// </summary>
        /// <returns></returns>
        public ReturnResult GetERPTasks(string condition, string typesCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select distinct top 12 m.cCVCode code,w.cWhName wareName,m.cWhCode wareCode");
                if (typesCode == "pc-position") //货位盘点
                {
                    sb.Append(",s.cPosition positionCode, po.cPosName positionName");
                }
                else if (typesCode == "pc-pro")//存货盘点 
                {
                    sb.Append(",s.cInvCode proCode, p.cInvName proName, p.cInvStd spec");
                }
                else if (typesCode == "pc-pospro")//货位存货盘点
                {
                    sb.Append(",s.cPosition positionCode, po.cPosName positionName,s.cInvCode proCode");
                    sb.Append(", p.cInvName proName, p.cInvStd spec ");
                }
                sb.Append(",Sum(convert(decimal(18,2),iCVQuantity)) number ");
                sb.Append(" from CheckVouchs s inner join CheckVouch m  on m.cCVCode = s.cCVCode and m.dveridate is null ");
                sb.Append(" inner join Inventory p on p.cInvCode = s.cInvCode ");
                sb.Append(" inner join Warehouse w on w.cWhCode = m.cWhCode ");
                sb.Append(" left join Position po on s.cPosition = po.cPosCode and po.cWhCode = w.cWhCode ");
                sb.Append(" where 1 = 1 ");
                #region 检索条件
                if (typesCode == "pc-position")
                {
                    sb.Append("and s.cPosition is not null ");
                }
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (obj.Name.Equals("types"))
                        {
                            continue;
                        }
                        else if (obj.Name.Equals("code"))
                        {
                            sb.Append(" and s.cCVCode like '%" + obj.Value.ToString() + "%' ");
                        }
                        else
                        {
                            sb.Append(" and " + obj.Name.ToString() + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                #endregion
                sb.Append(" group by m.cCVCode ,w.cWhName ,m.cWhCode ");
                if (typesCode == "pc-position") //货位盘点
                {
                    sb.Append(",s.cPosition , po.cPosName ");
                }
                else if (typesCode == "pc-pro")//存货盘点 
                {
                    sb.Append(",s.cInvCode,p.cInvName , p.cInvStd ");
                }
                else if (typesCode == "pc-pospro") //货位存货盘点
                {
                    sb.Append(",s.cPosition, po.cPosName,s.cInvCode");
                    sb.Append(",p.cInvName , p.cInvStd ");
                }
                sb.Append(" order by m.cCVCode desc ");
                var table = cu_helper.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                var list = cmd.TableToDictionary(table);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 创建盘点清单
        /// </summary>
        /// <returns></returns>
        private ReturnResult CreateTaskData(DbCheckTaskInfo taskInfo)
        {
            rsl = new ReturnResult();
            try
            {
                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                //foreach (DbCheckTaskInfo item in list)
                //{
                sb.Clear();
                sb.Append("insert into pCh_CheckTask_list");
                sb.Append(" (barCode,proCode,proName,color,shangbiao,number,createtime,pchCode,fatherCode) ");
                sb.Append("select b.barCode,b.proCode,b.proName,'','',1,'" + getNow() + "',");

                //sb.Append("'" + item.pchCode + "',''");
                sb.Append("'" + taskInfo.pchCode + "',''");

                sb.Append(" from V_BarCode_Info b where ");

                sb.Append(" barStatus='need-out'  and wareHouse='" + taskInfo.erpWareCode + "' ");
                if (!string.IsNullOrWhiteSpace(taskInfo.erpProCode))
                {
                    sb.Append("and ( ");
                    var arr = taskInfo.erpProCode.ToString().Split(',');
                    string procodes = "";
                    foreach (var s in arr)
                    {
                        //procodes = procodes+ "'" + s + "',";
                        sb.Append(" b.proCode like '%" + s + "%' or ");
                    }
                    //sb.Append(" and (b.proCode in (" + procodes.TrimEnd(',') + ") or  b.proCode='"+ taskInfo.erpProCode + "' )");
                    //sb.Append(" and b.proCode like '%" + procodes.TrimEnd(',') + "%' ");
                    sb.Remove(sb.Length - 3, 3);
                    sb.Append(") ");
                }
                if (!string.IsNullOrWhiteSpace(taskInfo.erpPositionCode))
                {
                    sb.Append(" and warePosition in('" + taskInfo.erpPositionCode + "')");
                }

                sb.Append(" and baseCode='" + userLogin.UserInfo().baseCode + "' ");

                sqlList.Add(sb.ToString());
                //}

                rsl = cmd.MoreUpdate(sqlList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 盘点任务列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetTaskList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                #region 检索条件
                StringBuilder sb = new StringBuilder();
                string where = "";
                sb.Append(" isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()) && obj.Name != "proName")
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "proName")
                            {
                                where = obj.Value.ToString();
                                continue;
                            }
                            else if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string newSta = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        newSta += "'" + s + "',";
                                    }
                                }
                                sb.Append(" status in (" + newSta.TrimEnd(',') + ")");
                            }
                            else
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                #endregion
                var list = cmd.PageList("V_pch_ProCheckTask_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                //var list = cmd.PageList<ViewInventoryTask>("V_InventoryTask_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                var newlist = new List<Dictionary<string, string>>();//按存货名字查询后的新列表

                #region 根据存货名称过滤  
                //多行创建一个盘点任务时，由于货位、存货可能是多个，视图关联不出来，所以这再查询一下
                foreach (var item in list)
                {
                    //if (!string.IsNullOrWhiteSpace(item["erpProCode"]) && string.IsNullOrEmpty(item["proName"]))
                    //{
                    //    var arr = item["erpProCode"].ToString().Split(',');
                    //    string procodes = "";
                    //    foreach (var s in arr)
                    //    {
                    //        procodes = procodes + "'" + s + "',";
                    //    }
                    //    sb.Clear();
                    //    sb.Append("select * from fun_Inventory_Info where isDel=0 and status='Y' and ");
                    //    sb.Append("baseCode='" + userLogin.UserInfo().baseCode + "'and proCode in (" + procodes.TrimEnd(',') + ")");
                    //    var proTable = cmd.GetDataTable(sb.ToString());
                    //    var proName = "";
                    //    foreach (DataRow dr in proTable.Rows)
                    //    {
                    //        proName = proName + dr["proName"] + ",";
                    //    }
                    //    item["proName"] = proName.TrimEnd(',');
                    //}

                    #region where存的是检索条件中的存货名称，按存货名称查时，不包含这个名字的过滤掉
                    if (!string.IsNullOrEmpty(where) && item["proName"].Contains(where))
                    {
                        newlist.Add(item);
                    }
                    #endregion

                    if (!string.IsNullOrWhiteSpace(item["erpPositionCode"]) && string.IsNullOrEmpty(item["positionName"]))
                    {
                        var posCode = ""; var posName = "";
                        foreach (var s in item["erpPositionCode"].Split(','))
                        {
                            posCode = posCode + "'" + s + "',";
                        }
                        sb.Clear();
                        sb.Append("select * from fun_CommonData_Info where cType='wp'and isDel=0 and status='Y' and ");
                        sb.Append("specFile='" + userLogin.UserInfo().baseCode + "' and cCode in (" + posCode.TrimEnd(',') + ") ");
                        var posTable = cmd.GetDataTable(sb.ToString());

                        foreach (DataRow dr in posTable.Rows)
                        {
                            posName = posName + dr["cName"] + ",";
                        }
                        item["positionName"] = posName.TrimEnd(',');

                    }
                }
                #endregion

                if (newlist.Count > 0)
                    rsl.Data = newlist;
                else
                    rsl.Data = list;

                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据盘点存货和仓库列出应盘列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="typesCode">盘点编码 </param>
        /// <returns></returns>
        public ReturnResult getYpList(string pageIndex, string pageSize, ref string pageCount, string condition, string typesCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                //sb.Append("select l.*,b.number num,b.proWeight from pCh_CheckTask_list l ");

                //sb.Append("select l.barCode,l.proCode,l.proName,l.pchCode,l.createtime,s.number num,b.proWeight ,s.color ,s.trademark ");
                //sb.Append(" from pCh_CheckTask_list l inner join V_BarCode_Info b on l.barCode=b.barCode ");
                //sb.Append(" inner join bar_ProductBarCode_Sub_info s on s.barCode = b.barCode ");
                
                sb.Append("select l.barCode,s.proCode,s.proName,l.pchCode,l.createtime,s.number num, s.color ,s.trademark shangbiao ");
                sb.Append(" from pCh_CheckTask_list l left join bar_ProductBarCode_Sub_info s on s.barCode = l.barCode ");

                var tableName = sb.ToString();
                sb.Clear();
                sb.Append(" pchCode = '" + typesCode + "'");
                if (!string.IsNullOrWhiteSpace(json["barCode"].ToString()))
                {
                    sb.Append(" and barCode like '%" + json["barCode"].ToString() + "%'");
                }
                if (!string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    sb.Append(" and proCode='" + json["proCode"].ToString() + "'");
                }
                if (!string.IsNullOrWhiteSpace(json["proName"].ToString()))
                {
                    sb.Append(" and proName like '%" + json["proName"].ToString() + "%'");
                }

                var sqlWhere = sb.ToString();
                var orderStr = " createtime desc ";
                var pageNumber = "0";  //总页数
                //rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                var dataTable = cmd.PageTableList(tableName, "1", pageSize, sqlWhere, orderStr, ref pageCount, ref pageNumber);
                rsl.Data = cmd.TableToDictionary(dataTable);
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据盘点编码获取盘点记录表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getTaskRecordsByCode(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select r.*,b.number,u.userName,b.proWeight from pch_CheckTask_records r");
                sb.Append(" inner join bar_ProductBarCode_info b on r.barCode=b.barCode ");
                sb.Append(" inner join sys_users_info u on r.createuser=u.userCode");
                sb.Append(" where 1=1 and pchCode='" + json["pchCode"] + "'");

                if (!string.IsNullOrWhiteSpace(json["barCode"].ToString()))
                {
                    sb.Append(" and r.barCode like '%" + json["barCode"].ToString() + "%'");
                }
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 盘点记录信息保存(移动端)
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddTaskRecords(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                var json = JsonConvert.DeserializeObject<JObject>(datas);
          
                if (string.IsNullOrWhiteSpace(json["pchCode"].ToString()))
                {
                    rsl.Message = "盘点编码不能为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();

                #region 盘点编码验证
                sb.Append("select * from pCh_CheckTask_info where ");
                sb.Append("pchCode='" + json["pchCode"].ToString() + "' and ");
                sb.Append("isDel=0 and status='pct-doing'");
                var venTable = cmd.GetDataTable(sb.ToString());
                if (venTable.Rows.Count < 1)
                {
                    rsl.Message = "盘点单号无效";
                    return rsl;
                }
                #endregion

                #region 重复盘点
                sb.Clear();
                sb.Append("select barCode from pch_CheckTask_records where ");
                sb.Append(" pchCode='" + json["pchCode"].ToString() + "'");
                sb.Append(" and barCode='" + json["barCode"].ToString() + "'");
                var qTable = cmd.GetDataTable(sb.ToString());
                if (qTable.Rows.Count > 0)
                {
                    rsl.Message = "条码已存在记录,禁止重复盘点";
                    return rsl;
                }
                #endregion

                #region 条码信息显示
                sb.Clear();
                sb.Append("select * from bar_ProductBoxCode_info where barCode='" + json["barCode"].ToString() + "'");
                qTable = cmd.GetDataTable(sb.ToString());
                string barType = "Bar";
                DbCheckTaskRecords re;
                List<Dictionary<string, string>> barList = new List<Dictionary<string, string>>();
                if (qTable.Rows.Count < 1)
                {
                    #region 非箱码
                    sb.Clear();
                    sb.Append("select * from bar_ProductBarCode_info where barCode='" + json["barCode"].ToString() + "'");
                    var barTable = cmd.GetDataTable(sb.ToString());
                    if (barTable.Rows.Count > 0)
                    {
                        barList = cmd.TableToDictionary(barTable);
                    }
                    else
                    {
                        rsl.Result = false;
                        rsl.Message = "此码为无效码";
                        return rsl;
                    }
                    #endregion
                }
                else
                {
                    #region 箱码
                    barType = "Box";
                    if (qTable.Rows[0]["isFull"].ToString() == "ful")
                    {
                        #region 满箱状态，扫描箱码系统视为箱内条码全部扫描
                        sb.Clear();
                        sb.Append("select * from bar_ProductBarCode_info where boxCode='" + json["barCode"].ToString() + "'");
                        qTable = cmd.GetDataTable(sb.ToString());
                        foreach (DataRow r in qTable.Rows)
                        {
                            re = new DbCheckTaskRecords();
                            re.pchCode = json["pchCode"].ToString();
                            re.status = "Y";
                            re.barType = "Bar";
                            re.memo = "关联盘点(与箱码相关)";//不得随意更改，盘点报告有用到
                            re.Id = Guid.NewGuid().ToString().ToLower().Replace("-", "");
                            re.createuser = json["userCode"].ToString();
                            re.createtime = getNow();
                            re.barCode = r["barCode"].ToString();
                            oper = new OperateModel();
                            oper.Data = re;
                            oper.Types = OperateModel.OperateType.Add;
                            list.Add(oper);
                        }
                        barList = cmd.TableToDictionary(qTable);
                        #endregion
                    }
                    else
                    {
                        rsl.Message = "此箱码非满箱，请扫箱内条码盘点";
                        return rsl;
                    }
                    #endregion
                }
                #endregion

                #region 记录保存
                re = new DbCheckTaskRecords();
                re.barCode = json["barCode"].ToString();
                re.createtime = getNow();
                re.createuser = json["createuser"].ToString();
                re.barType = barType;
                re.Id = Guid.NewGuid().ToString().ToLower().Replace("-", "");
                re.status = "Y";
                re.pchCode = json["pchCode"].ToString();
                oper = new OperateModel();
                oper.Data = re;
                oper.Types = OperateModel.OperateType.Add;
                list.Add(oper);
                #endregion

                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                    if (rsl.Result)
                    {
                        rsl.Data = barList;
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除盘点记录（移动端）
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult DelTaskRecords(string jsonStr)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                List<string> sqlList = new List<string>();
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传入的参数不能为空";
                    rsl.Result = false;
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                sb.Append("delete from pCh_CheckTask_records ");
                sb.Append(" where pchCode = '" + json["pchCode"].ToString() + "'");
                sb.Append(" and barCode='"+ json["barCode"].ToString() + "''");
                sqlList.Add(sb.ToString());

                sb = new StringBuilder();
                sb.Append("select * from bar_ProductBoxCode_info where barCode='" + json["barCode"].ToString() + "'");
                var qTable = cmd.GetDataTable(sb.ToString());
                if (qTable.Rows.Count > 0)
                {
                    sb.Clear();
                    sb.Append("delete from pCh_CheckTask_info where pchCode = '" + json["pchCode"].ToString() + "'");
                    sb.Append(" and barCode in(select barCode from bar_ProductBarCode_info ");
                    sb.Append("where boxCode='"+ json["barCode"].ToString() + "')");
                    sqlList.Add(sb.ToString());
                }
                rsl = cmd.MoreUpdate(sqlList);
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除盘点任务
        /// </summary>
        /// <param name="pchCode"></param>
        /// <returns></returns>
        public ReturnResult DelCheckTask(string pchCode)
        {
            rsl = new ReturnResult();
            try
            {
               List<string> sqlList = new List<string>();  
                StringBuilder sb = new StringBuilder();
                sb.Append("update pCh_CheckTask_info set isdel=1,delDate='"+ getNow() +"' ");
                sb.Append(",deluser='"+ userLogin.UserInfo().userCode +"' ");
                sb.Append("where pchCode='"+ pchCode +"'");
                sqlList.Add(sb.ToString());
                sb = new StringBuilder();
                sb.Append("delete from pCh_CheckTask_list where pchCode='"+ pchCode +"'");
                sqlList.Add(sb.ToString());
                sb = new StringBuilder();
                sb.Append("delete from pCh_CheckTask_records where pchCode='" + pchCode + "'");
                sqlList.Add(sb.ToString());
                rsl = cmd.MoreUpdate(sqlList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 更改盘点任务状态
        /// </summary>
        /// <param name="pchCode">盘点单号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public ReturnResult ChanageStatus(string pchCode,string status)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                DbCheckTaskInfo task;
                task = new DbCheckTaskInfo();
                task.pchCode = pchCode;
                task.status = status;
                oper = new OperateModel();
                oper.Data = task;
                oper.Conditions = "pchCode";
                oper.Types = OperateModel.OperateType.Edit;
                operList.Add(oper);

                DbApproveRecord appRd;
                appRd = new DbApproveRecord();
                appRd.businessType = "PCH";
                appRd.businessCode = pchCode;
                appRd.result = status;
                appRd.createtime = getNow();
                appRd.createuser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Data = appRd;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);

                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 生成盘点报告
        /// </summary>
        /// <param name="pchCodes"></param>
        /// <returns></returns>
        public ReturnResult createReport(string pchCodes)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                operList = new List<OperateModel>();
                if (string.IsNullOrWhiteSpace(pchCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }
                var arr = pchCodes.Split(',');
                List<Dictionary<string, string>> reportList = new List<Dictionary<string, string>>();
                Dictionary<string, string> dic;
                DbCheckTaskReport re;
                DbCheckTaskReportDiffer dif;
                DbCheckTaskInfo task;
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {
                      
                        StringBuilder sb = new StringBuilder();
                        sb.Append("select * from V_pch_ProCheckTask_info where ");
                        sb.Append(" pchCode='" + code + "'");
                        var taskTable = cmd.GetDataTable(sb.ToString());//获取盘点任务信息
                        sb.Clear();
                        sb.Append("select l.*,b.number from pCh_CheckTask_list l");
                        sb.Append(" inner join bar_ProductBarCode_info b on l.barCode=b.barCode");
                        sb.Append(" where l.pchCode='" + code + "'");
                        var qdTable= cmd.GetDataTable(sb.ToString());//盘点清单(应盘)
                        sb.Clear();
                        sb.Append("select r.*,b.number from pCh_CheckTask_records r");
                        sb.Append(" inner join bar_ProductBarCode_info b on r.barCode=b.barCode");
                        sb.Append(" where r.pchCode='" + code + "' "); // and r.barType='Bar'
                        var rdTable = cmd.GetDataTable(sb.ToString());//盘点记录(实盘)
                        double pkNum=0,pyNum=0,ypNum=0,spNum=0;//盘亏、盘盈、应盘、实盘
                        List<Dictionary<string,string>> pkList=new List<Dictionary<string, string>>();//盘亏数据集合
                        List<Dictionary<string, string>> pyList = new List<Dictionary<string, string>>();//盘盈数据集合
                        #region 盘亏
                        foreach (DataRow r in qdTable.Rows)
                        {
                            bool ispk = true;
                            foreach (DataRow rd in rdTable.Rows)
                            {
                                if (r["barCode"].ToString() == rd["barCode"].ToString())
                                {
                                    ispk = false;
                                    break;
                                }
                            }
                            if (ispk)
                            {
                                dic = new Dictionary<string, string>();
                                dic["barCode"] = r["barCode"].ToString();
                                dic["number"] = r["number"].ToString();
                                pkNum += double.Parse(r["number1"].ToString());
                                pkList.Add(dic);
                            }
                           
                        }
                        #endregion

                        #region 盘盈
                        foreach (DataRow r in rdTable.Rows)
                        {
                            bool ispy = true;
                            foreach (DataRow rd in qdTable.Rows)
                            {
                                if (r["barCode"].ToString() == rd["barCode"].ToString())
                                {
                                    ispy = false;
                                    break;
                                }
                            }
                            if (ispy)
                            {
                                dic = new Dictionary<string, string>();
                                dic["barCode"] = r["barCode"].ToString();
                                dic["number"] = "1";
                                pyNum += double.Parse(r["number"].ToString());
                                pyList.Add(dic);
                            }

                        }
                        #endregion

                        #region 应盘/实盘
                        foreach (DataRow rd in qdTable.Rows)
                        {
                            ypNum += double.Parse(rd["number1"].ToString());
                        }
                        foreach (DataRow rd in rdTable.Rows)
                        {
                            spNum += double.Parse(rd["number"].ToString());
                        }
                        #endregion

                        #region 盘点报表主表
                        re = new DbCheckTaskReport();
                        re.pchCode = code;//盘点单号
                        re.ypNum = ypNum.ToString();//系统应盘数量
                        re.ypCount = qdTable.Rows.Count.ToString();//系统应盘件数
                        re.spNum = spNum.ToString();
                        re.spCount = rdTable.Rows.Count.ToString();
                        re.pkCount = pkList.Count.ToString();
                        re.pkNum = pkNum.ToString();
                        re.pyCount = pyList.Count.ToString();
                        re.pyNum = pyNum.ToString();
                        re.createtime = getNow();
                        re.createuser = userLogin.UserInfo().userCode;
                        re.isSync = 0;
                        oper = new OperateModel();
                        oper.Data = re;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion

                        #region 盘盈/盘亏数据
                        foreach (var d in pkList)
                        {
                            dif = new DbCheckTaskReportDiffer();
                            dif.barCode = d["barCode"].ToString();
                            dif.barType = "Bar";
                            dif.done = "0";
                            dif.pchCode = code;
                            dif.types = "0";
                            oper = new OperateModel();
                            oper.Data = dif;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                        }
                        foreach (var d in pyList)
                        {
                            dif = new DbCheckTaskReportDiffer();
                            dif.barCode = d["barCode"].ToString();
                            dif.barType = "Bar";
                            dif.done = "0";
                            dif.pchCode = code;
                            dif.types = "1";
                            oper = new OperateModel();
                            oper.Data = dif;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                        }
                        #endregion

                        #region 更改盘点单状态
                        task = new DbCheckTaskInfo();
                        task.pchCode = code;
                        task.status = "pct-report";
                        oper = new OperateModel();
                        oper.Data = task;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "pchCode";
                        operList.Add(oper);
                        #endregion
                    }
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有生成任何数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 盘点报告数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult TaskReportList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" 1=1 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                var list = cmd.PageList("V_pch_proCheckTask_report", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);


                var newlist = new List<Dictionary<string, string>>();//按存货名字查询后的新列表

                #region 、多行创建一个盘点任务时，由于货位、存货可能是多个，视图关联不出来，所以这再查询一下 已注释
                //foreach (var item in list)
                //{
                //    if (!string.IsNullOrWhiteSpace(item["erpProCode"]) && string.IsNullOrEmpty(item["proName"]))
                //    {
                //        var arr = item["erpProCode"].ToString().Split(',');
                //        string procodes = "";
                //        foreach (var s in arr)
                //        {
                //            procodes = procodes + "'" + s + "',";
                //        }
                //        sb.Clear();
                //        sb.Append("select * from fun_Inventory_Info where isDel=0 and status='Y' and ");
                //        sb.Append("baseCode='" + userLogin.UserInfo().baseCode + "'and proCode in (" + procodes.TrimEnd(',') + ")");
                //        var proTable = cmd.GetDataTable(sb.ToString());
                //        var proName = "";
                //        foreach (DataRow dr in proTable.Rows)
                //        {
                //            proName = proName + dr["proName"] + ",";
                //        }
                //        item["proName"] = proName.TrimEnd(',');
                //    }

                //    #region where存的是检索条件中的存货名称，按存货名称查时，不包含这个名字的过滤掉
                //    if (!string.IsNullOrEmpty(sb.ToString()) && item["proName"].Contains(sb.ToString()))
                //    {
                //        newlist.Add(item);
                //    }
                //    #endregion

                //    if (!string.IsNullOrWhiteSpace(item["erpPositionCode"]) && string.IsNullOrEmpty(item["positionName"]))
                //    {
                //        var posCode = ""; var posName = "";
                //        foreach (var s in item["erpPositionCode"].Split(','))
                //        {
                //            posCode = posCode + "'" + s + "',";
                //        }
                //        sb.Clear();
                //        sb.Append("select * from fun_CommonData_Info where cType='wp'and isDel=0 and status='Y' and ");
                //        sb.Append("specFile='" + userLogin.UserInfo().baseCode + "' and cCode in (" + posCode.TrimEnd(',') + ") ");
                //        var posTable = cmd.GetDataTable(sb.ToString());

                //        foreach (DataRow dr in posTable.Rows)
                //        {
                //            posName = posName + dr["cName"] + ",";
                //        }
                //        item["positionName"] = posName.TrimEnd(',');

                //    }
                //}
                #endregion

                if (newlist.Count > 0)
                    rsl.Data = newlist;
                else
                    rsl.Data = list;

                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除盘点报告
        /// </summary>
        /// <param name="pchCode">盘点单号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public ReturnResult delReport(string pchCodes)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(pchCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }
                var arr = pchCodes.Split(',');
                operList = new List<OperateModel>();
                List<string> sqlList = new List<string>();
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {
                        //删除盘点报告
                        DbCheckTaskReport report;
                        report = new DbCheckTaskReport();
                        report.pchCode = code;
                        oper = new OperateModel();
                        oper.Data = report;
                        oper.Conditions = "pchCode";
                        oper.Types = OperateModel.OperateType.Delete;
                        operList.Add(oper);
                        //修改盘点任务状态
                        DbCheckTaskInfo taskInfo;
                        taskInfo = new DbCheckTaskInfo();
                        taskInfo.pchCode = code;
                        taskInfo.status = "pct-doing";
                        oper = new OperateModel();
                        oper.Data = taskInfo;
                        oper.Conditions = "pchCode";
                        oper.Types = OperateModel.OperateType.Edit;
                        operList.Add(oper);
                        //删除相关盘点差异记录
                        DbCheckTaskReportDiffer diff = new DbCheckTaskReportDiffer();
                        diff.pchCode = code;
                        oper = new OperateModel();
                        oper.Data = diff;
                        oper.Conditions = "pchCode";
                        oper.Types = OperateModel.OperateType.Delete;
                        operList.Add(oper);
                        //将U8中调整出库、调整入库设回默认（0）
                        sb.Clear();
                        sb.Append("select re.*,erpId,erpNumber from pCh_CheckTask_report re ");
                        sb.Append("inner join pCh_CheckTask_info info on re.pchCode=info.pchCode ");
                        sb.Append("where re.pchCode='" + code + "' ");
                        var table = cmd.GetDataTable(sb.ToString());
                        if (table.Rows.Count > 0)
                        {
                            sb.Clear();
                            sb.Append("update CheckVouchs set iAdOutQuantity='0',iAdInQuantity ='0' where autoID='" + table.Rows[0]["erpId"] + "'");
                        }
                        sqlList.Add(sb.ToString());
                    }
                }

                rsl = cmd.MoreUpdate(operList);
                if(rsl.Result)
                    rsl = cu_helper.TransUpdate(sqlList, null, userLogin.UserInfo().baseCode);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取盘点差异数据
        /// </summary>
        /// <param name="venCode">盘点任务编码</param>
        /// <param name="barType">条码类型 Bar 条码</param>
        /// <param name="types">盈亏类型(1盈 0亏)</param>
        /// <returns></returns>
        public ReturnResult getReportDiffer(string pchCode, string barType, string types)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select d.*,b.number from pCh_CheckTask_reportDiffer d  ");
                sb.Append(" inner join bar_ProductBarCode_info b on d.barCode=b.barCode ");
                sb.Append(" where pchCode='" + pchCode + "' and d.barType='" + barType + "' ");
                sb.Append("and types='" + types + "'");
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i]["done"] == "0")
                    {
                        list[i]["done"] = "未处理";
                    }
                    else
                    {
                        list[i]["done"] = "已处理";
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 更新盘点差异数据信息
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="barType"></param>
        /// <param name="entryType"></param>
        /// <returns></returns>
        public ReturnResult DoCheckDiffers(string ids, string barType, string entryType)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            List<string> sqlList = new List<string>();
            List<OperateModel> operList = new List<OperateModel>();
            try
            {
                #region 获取仓库、货位信息
                sb.Append("select erpWareCode,erpPositionCode from pCh_CheckTask_info where pchCode in (");
                sb.Append("select distinct pchCode from pCh_CheckTask_reportDiffer where id in(" + ids + "))");
                var vTable = cmd.GetDataTable(sb.ToString());
                string wareCode = "0", positionCode="0",bars="";
                if (vTable.Rows.Count > 0)
                {
                    wareCode = vTable.Rows[0]["erpWareCode"].ToString();
                    positionCode = vTable.Rows[0]["erpPositionCode"].ToString();
                }
                #endregion

                #region 获取需要处理的条码信息
                sb.Clear();
                sb.Append("select d.barCode ,b.number from pCh_CheckTask_reportDiffer d ");
                sb.Append(" inner join bar_ProductBarCode_info b on d.barCode=b.barCode ");
                sb.Append(" where d.id in(" + ids + ")");
                var barTable = cmd.GetDataTable(sb.ToString());
                if (barTable.Rows.Count > 0)
                {
                    foreach (DataRow dr in barTable.Rows)
                    {
                        bars = bars + dr["barCode"] + "-" + dr["number"] + ",";
                    }
                }
                #endregion

                #region  新增出入库记录 、 修改条码状态信息
                #region 获取出入库编码
                string mcode = DateTime.Now.ToString("yyyyMMddhhmmss");
                #endregion

                #region 主表添加
                //sb.Clear();
                //sb.Append("insert into bar_BarEntryRecords_main(mCode,mType,happenDate,wareHouse,maker,createtime,createuser,status,deptCode,");
                //sb.Append("outOrderCode,memo,isForm,inOutType,baseCode,isBlue,goodsPosition) values ('"+ mCode + "','11','"+);
                DbBarRecordsMain main = new DbBarRecordsMain();
                main.mCode = mcode;
                main.mType = "11";
                main.happenDate = DateTime.Now.ToString("yyyy-MM-dd");
                main.wareHouse = wareCode;
                main.maker = userLogin.UserInfo().userCode;
                main.createtime = DateTime.Now.ToString();
                main.createuser = userLogin.UserInfo().userCode;
                main.status = "needAudit";
                //main.deptCode = ;
                //main.outOrderCode = ;
                main.memo = "盘点差异调整";
                main.isForm = "PC";
                if (entryType == "1")//盘亏 做出库
                    //main.inOutType = "pitz";
                    main.inOutType = "potz";
                else
                    //main.inOutType = "potz";
                    main.inOutType = "pitz";
                main.baseCode = userLogin.UserInfo().baseCode;
                main.isBlue = "1";
                main.goodsPosition = positionCode;

                oper = new OperateModel();
                oper.Data = main;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                #endregion

                foreach (string s in bars.TrimEnd(',').Split(','))
                {
                    #region  子表添加
                    DbBarRecordsList dbList = new DbBarRecordsList();
                    dbList.mCode = mcode;
                    dbList.barCode = s.Split('-')[0];
                    dbList.num = s.Split('-')[1];
                    dbList.status = "Y";
                    dbList.createtime = DateTime.Now.ToString();
                    dbList.createuser = userLogin.UserInfo().userCode;
                    if (entryType == "1")
                        dbList.inOutType = "potz";
                    else
                        dbList.inOutType = "pitz";

                    oper = new OperateModel();
                    oper.Data = dbList;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion

                    #region 条码 仓库、货位、状态修改
                    DbProductBar bar = new DbProductBar();
                    bar.wareHouse = wareCode;
                    bar.warePosition = positionCode;
                    bar.memo= "盘点差异处理  "+getNow() + "(" + userLogin.UserInfo().userCode + ")";
                    if (entryType == "1")//盘亏 做出库
                        bar.barStatus = "bar-finish";
                    else
                        bar.barStatus = "need-out";

                    bar.barCode= s.Split('-')[0];

                    oper = new OperateModel();
                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "barCode";
                    operList.Add(oper);

                    #endregion
                }
                #endregion

                #region 修改条码差异为已处理
                foreach (string s in ids.Split(','))
                {
                    DbCheckTaskReportDiffer dif = new DbCheckTaskReportDiffer();
                    dif.id = Convert.ToInt32(s);
                    dif.done = "1";
                    dif.memo = getNow() + "(" + userLogin.UserInfo().userCode + ")";

                    oper = new OperateModel();
                    oper.Data = dif;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                }
                
                #endregion

                rsl = cmd.MoreUpdate(operList);

                if (rsl.Result)
                {
                    txt.AddLogMsg("差异数据操作：" + JsonConvert.SerializeObject(operList));
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 同步盘点结果
        /// </summary>
        /// <returns></returns>
        public ReturnResult syncReport(string pchCodes)
        {
            CuDbHelper cu_helper = new CuDbHelper();
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            List<string> U8List = new List<string>();
            List<string> sqlList = new List<string>();

            try
            {
                if (string.IsNullOrWhiteSpace(pchCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }

                var errMsg = "";
                var pCarr = pchCodes.Split(',');

                foreach (string code in pCarr)
                {
                    #region 报告已同步 不再同步
                    sb.Clear();
                    sb.Append("select isSync,venCode from V_pch_proCheckTask_report where pchCode ='" + code + "'");
                    var rptable = cmd.GetDataTable(sb.ToString());
                    if (rptable.Rows[0][0].ToString().Equals("1"))
                    {
                        rsl.Message = rptable.Rows[0]["venCode"].ToString() +"已同步，不再继续同步。";
                        continue;
                    }
                    #endregion

                    var erpCode = ""; var erpPosition = ""; var erpProCode = ""; var chType = "";//盘点单号，盘点货位，盘点存货，盘点类型
                    #region 获取盘点货位、盘点存货和盘点类型
                    sb.Clear();
                    sb.Append("select erpCode,erpProCode,erpPositionCode,chType from pCh_CheckTask_info where pchCode='" + code + "'");
                    var table = cmd.GetDataTable(sb.ToString()); //盘点单列表
                    erpPosition = table.Rows[0]["erpPositionCode"].ToString();//盘点货位
                    chType = table.Rows[0]["chType"].ToString();//盘点类型

                    var erpProCodes = table.Rows[0]["erpProCode"].ToString();//盘点存货
                    foreach (var s in erpProCodes.Split(','))
                    {
                        erpProCode += "'" + s + "',";
                    }

                    #endregion

                    #region 物控实盘
                    var spTable = getSPPros(code,ref errMsg);//实盘列表
                    if(!string.IsNullOrWhiteSpace(errMsg)){
                        rsl.Message = errMsg;
                        return rsl;
                    }
                    //如果实盘列表为空，查盘点单列表获取U8盘点单号
                    if (spTable.Rows.Count < 1)
                    {
                        erpCode = table.Rows[0]["erpCode"].ToString();//U8盘点单号
                    }
                    else
                    {
                        erpCode = spTable.Rows[0]["erpCode"].ToString();//U8盘点单号
                    }
                    #endregion

                    List<string> cyList = new List<string>(); //盘盈盘亏中  不在 U8盘点单中盘点 的存货（编码、颜色、商标）
                    #region  （只 货位存货盘点 ） 获取盘盈盘亏中 不在 U8盘点单中盘点 的存货（编码、颜色、商标）
                    if (chType == "pc-pospro") 
                    { 
                        sb.Clear();
                        sb.Append("select s.proCode,s.color,s.trademark ");
                        sb.Append("from pCh_CheckTask_reportDiffer d ");
                        sb.Append("left join bar_ProductBarCode_Sub_info s on s.barCode = d.barCode ");
                        sb.Append("where pchCode = '"+ code + "' ");
                        sb.Append("group by s.proCode, s.color, s.trademark ");
                        sb.Append("except ");//取差集
                        sb.Append("select cInvCode proCode, cFree1 color, cFree3 trademark ");
                        sb.Append("from UFDATA_888_2015..CheckVouchs where cCVCode = '" + erpCode + "' ");
                        sb.Append("and cInvCode in (" + erpProCode.TrimEnd(',') + " ) ");
                        //sb.Append("select s.proCode,s.color,s.trademark ");
                        //sb.Append("from pCh_CheckTask_records r ");
                        //sb.Append("left join bar_ProductBarCode_Sub_info s on s.barCode = r.barCode ");
                        //sb.Append("where pchCode = '" + code + "' ");
                        //sb.Append("group by s.proCode, s.color, s.trademark ");
                        var cyTable = cmd.GetDataTable(sb.ToString());//盘亏盘盈列表
                        if (cyTable.Rows.Count > 0)
                        {
                            foreach (DataRow s in cyTable.Rows)
                            {
                                cyList.Add(s["proCode"].ToString() + "," + s["color"].ToString() + "," + s["trademark"].ToString());
                            }
                        }
                    }
                    #endregion

                    #region 汇总盘亏盘盈列表 (不在 U8盘点单中盘点 的存货)
                    sb.Clear();
                    sb.Append("select d.types,d.done,s.proCode,s.proName,s.color,s.trademark,sum(convert(decimal(18,0),s.number)) number ,count(*) barCount ");
                    sb.Append("from pCh_CheckTask_reportDiffer d left join bar_ProductBarCode_Sub_info s on s.barCode=d.barCode ");
                    sb.Append("where  pchCode='" + code + "' "); 
                    sb.Append("group by d.types,d.done,s.proCode, s.proName, s.color, s.trademark");
                    var ykTable = cmd.GetDataTable(sb.ToString());//盘亏盘盈列表

                    var isDone = ykTable.Select("done='0' ");

                    #region 如果有需要差异处理的条码，先做差异处理再同步
                    if (isDone.Length > 0)
                    {
                        rsl.Message = "请先对条码进行差异处理再同步盘点单";
                        return rsl;
                    }
                    #endregion

                    DataRow[] py = new DataRow[0],pk = new DataRow[0];

                    sb.Clear();
                    if (cyList != null && cyList.Count>0)
                    {
                        sb.Append(" and ( ");
                        foreach (var s in cyList)
                        {
                            var arrs = s.Split(',');
                            sb.Append(" (proCode='" + arrs[0] + "' and color='" + arrs[1] + "' and trademark='" + arrs[2] + "') or ");
                        }
                        sb.Remove(sb.Length - 3, 3);
                        sb.Append(")");

                        py = ykTable.Select("types='1'" + sb.ToString());//盘盈列表
                        pk = ykTable.Select("types='0'" + sb.ToString());//盘亏列表
                    }
                    

                    #endregion

                    #region 获取 U8盘点单子表  单据id表

                    #region U8盘点单子表
                    sb.Clear();
                    sb.Append("select * from CheckVouchs where cCVCode='" + erpCode + "' ");
                    var cvtable = cu_helper.getData(sb.ToString(), userLogin.UserInfo().baseCode);//U8盘点单子表
                    if (cvtable.Rows.Count < 1)
                    {
                        rsl.Message = "盘点单(" + erpCode + ")不存在或已删除，同步失败！";
                        return rsl;
                    }
                    #endregion

                    #region 单据id表
                    sb.Clear();
                    sb.Append("select * from UFSystem.dbo.UA_Identity where cVouchType = 'ch' and cAcc_Id = '" + userLogin.UserInfo().baseCode + "'");
                    var idTable = cu_helper.getData(sb.ToString(), userLogin.UserInfo().baseCode);// 单据id表
                    var iChildId = int.Parse(idTable.Rows[0]["iChildId"].ToString());
                    //var autoID = "1" + idTable.Rows[0]["iChildId"].ToString().PadLeft(9, '0');
                    var autoID = int.Parse("1" + idTable.Rows[0]["iChildId"].ToString().PadLeft(9, '0'));
                    #endregion

                    #endregion

                    #region 以物控实盘为准，查找U8盘点单子表，都有的话 修改盘点数量和盘点件数； 
                    //(货位存货盘点除外)物控有U8没有，则在U8新增行
                    //货位存货盘点:判断盘亏盘盈列表中是否有不在盘点任务中的存货，有的话查现存量，物控U8现存量不相等就新增行；没有盘亏盘盈条码就只修改盘点的存货实盘数量
                    var ID = cvtable.Rows[0]["ID"].ToString();
                    var unit = cvtable.Rows[0]["cAssUnit"].ToString();
                    var rowNo = int.Parse(cvtable.Rows[cvtable.Rows.Count - 1]["irowno"].ToString());
                    var change = false;

                    #region  修改盘点数量和新增行
                    foreach (DataRow dr in spTable.Rows)
                    {
                        sb.Clear();
                        //根据存货、颜色、商标查询子表账面数
                        var row = cvtable.Select("cInvCode='" + dr["proCode"] + "' and cFree1='" + dr["color"] +
                            "' and cFree3='" + dr["trademark"] + "'");
                        if (row.Length > 0)
                        {
                            sb.Append("update CheckVouchs set iCVCQuantity ='" + dr["number"].ToString() + "'");
                            sb.Append(",iCVCNum ='" + dr["barCount"].ToString() + "' where autoID='" + row[0]["autoID"] + "'");
                        }
                        else
                        {
                            if(chType!= "pc-pospro")
                            {
                                #region 直接新增行
                                change = true;
                                autoID += 1;
                                iChildId += 1;
                                rowNo += 1;
                                var cbsysbarcode = "||st18|" + erpCode + "|" + rowNo;

                                sb.Clear();
                                //物控有 U8没有  在U8新增行
                                //iCVQuantity 账面数量， iCVNum 账面辅计量数量（件数）， iCVCNum 盘点辅计量数量 ，iCVCQuantity 盘点数量（实盘数） 
                                sb.Append("insert into CheckVouchs(cCVCode,cInvCode,iCVNum,iCVQuantity,iCVCNum,iCVCQuantity,cFree1,");
                                sb.Append("cPosition,autoID,ID,iAdInQuantity,iAdInNum,iAdOutQuantity,iAdOutNum,cFree3,");
                                sb.Append("irowno,cbsysbarcode,cbufts) ");
                                sb.Append("values('" + erpCode + "','" + dr["proCode"] + "',0,0,'" + dr["barCount"].ToString());
                                //sb.Append("','" + dr["warePosition"] + "','" + autoID + "','" + ID );
                                sb.Append("','" + dr["number"].ToString() + "','" + dr["color"] + "','" + erpPosition + "','" + autoID + "','" + ID);
                                sb.Append("',0,0,0,0,'" + dr["trademark"] + "','" + rowNo + "','" + cbsysbarcode);
                                sb.Append("',DEFAULT)");
                                #endregion
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            U8List.Add(sb.ToString());
                        }
                        
                    }
                    #endregion

                    #region 货位存货盘点特殊处理
                    if (chType == "pc-pospro")
                    {
                        #region 现存量查询
                        var psTable = getPosSum(erpPosition,ref errMsg);//U8货位存量
                        if (!string.IsNullOrWhiteSpace(errMsg))
                        {
                            rsl.Message = errMsg;
                            return rsl;
                        }
                        var barTable = getBarPosSum(erpPosition ,ref errMsg);//纺智云货位存量
                        if (!string.IsNullOrWhiteSpace(errMsg))
                        {
                            rsl.Message = errMsg;
                            return rsl;
                        }
                        #endregion

                        DataRow[] uRows = null, rows = null;
                        double uStrock = 0, fStrock = 0, sp = 0;  //u8现存量  纺智云现存量  实际数量（U8+/-盘亏/盈数量）

                        #region 遍历盘亏、盘盈 存货列表，修改u8盘点单
                        for (int i = 0; i < 2; i++)
                        {
                            // = 0时遍历盘亏列表； = 1时遍历盘盈列表
                            var list = pk;
                            if (i > 0)
                            {
                                list = py;
                            }

                            foreach (var s in list)
                            {
                                sb.Clear();
                                uStrock = 0; fStrock = 0; sp = 0;
                                uRows = psTable.Select("cInvCode = '" + s["proCode"] + "' and cFree1 = '" + s["color"] + "' and cFree3 = '" + s["trademark"] + "'");
                                rows = barTable.Select("proCode = '" + s["proCode"] + "' and color = '" + s["color"] + "' and trademark = '" + s["trademark"] + "'");
                                if (uRows.Length > 0)
                                {
                                    uStrock = double.Parse(uRows[0]["iQuantity"].ToString());
                                }
                                if (rows.Length > 0)
                                {
                                    fStrock = double.Parse(rows[0]["number"].ToString());
                                }
                                if (uStrock != fStrock)
                                {
                                    if(i==0)
                                        sp = uStrock - double.Parse(s["number"].ToString()); //实盘数
                                    else
                                        sp = uStrock + double.Parse(s["number"].ToString()); //实盘数

                                    //根据存货、颜色、商标查询盘点单是否有这一行
                                    //有就修改实盘数  没有就新增一行
                                    var pdRow = cvtable.Select("cInvCode = '" + s["proCode"] + "' and cFree1 = '" + s["color"] + "' and cFree3 = '" + s["trademark"] + "'");
                                    if (pdRow.Length > 0)
                                    {
                                        sb.Append("update CheckVouchs set iCVCQuantity ='" + sp + "'");
                                        sb.Append(",iCVCNum ='" + s["barCount"].ToString() + "' where autoID='" + pdRow[0]["autoID"] + "'");
                                    }
                                    else
                                    {
                                        change = true;
                                        autoID += 1;
                                        iChildId += 1;
                                        rowNo += 1;
                                        var cbsysbarcode = "||st18|" + erpCode + "|" + rowNo;

                                        //iCVQuantity 账面数量， iCVNum 账面辅计量数量（件数）， iCVCNum 盘点辅计量数量 ，iCVCQuantity 盘点数量（实盘数） 
                                        sb.Append("insert into CheckVouchs(cCVCode,cInvCode,iCVNum,iCVQuantity,iCVCNum,iCVCQuantity,cFree1,");
                                        sb.Append("cPosition,autoID,ID,iAdInQuantity,iAdInNum,iAdOutQuantity,iAdOutNum,cFree3,");
                                        sb.Append("irowno,cbsysbarcode,cbufts) ");
                                        sb.Append("values('" + erpCode + "','" + s["proCode"] + "',0," + uStrock + ",'" + s["barCount"].ToString());
                                        sb.Append("','" + sp + "','" + s["color"] + "','" + erpPosition + "','" + autoID + "','" + ID);
                                        sb.Append("',0,0,0,0,'" + s["trademark"] + "','" + rowNo + "','" + cbsysbarcode);
                                        sb.Append("',DEFAULT)");
                                    }

                                }

                                if (!string.IsNullOrWhiteSpace(sb.ToString()))
                                {
                                    U8List.Add(sb.ToString());
                                }
                            }
                        }
                        #endregion

                        #region 分别针对盘亏、盘盈 存货列表，修改u8盘点单 已注释
                        #region 盘盈
                        //if (py.Length > 0)
                        //{
                        //    foreach (var s in py)
                        //    {
                        //        sb.Clear();
                        //        uStrock = 0; fStrock = 0; sp = 0;
                        //        uRows = psTable.Select("cInvCode = '" + s["proCode"] + "' and cFree1 = '" + s["color"] + "' and cFree3 = '" + s["trademark"] + "'");
                        //        rows = barTable.Select("proCode = '" + s["proCode"] + "' and color = '" + s["color"] + "' and trademark = '" + s["trademark"] + "'");
                        //        if (uRows.Length > 0)
                        //        {
                        //            uStrock = double.Parse(uRows[0]["iQuantity"].ToString());
                        //        }
                        //        if (rows.Length > 0)
                        //        {
                        //            fStrock = double.Parse(rows[0]["number"].ToString());
                        //        }
                        //        if (uStrock!= fStrock)
                        //        {
                        //            sp = uStrock + double.Parse(s["number"].ToString()); //实盘数

                        //            //根据存货、颜色、商标查询盘点单是否有这一行
                        //            //有就修改实盘数  没有就新增一行
                        //            var pdRow = cvtable.Select("cInvCode = '" + s["proCode"] + "' and cFree1 = '" + s["color"] + "' and cFree3 = '" + s["trademark"] + "'");
                        //            if (pdRow.Length > 0)
                        //            {
                        //                sb.Append("update CheckVouchs set iCVCQuantity ='" + sp + "'");
                        //                sb.Append(",iCVCNum ='" + s["barCount"].ToString() + "' where autoID='" + pdRow[0]["autoID"] + "'");
                        //            }
                        //            else
                        //            {
                        //                change = true;
                        //                autoID += 1;
                        //                iChildId += 1;
                        //                rowNo += 1;
                        //                var cbsysbarcode = "||st18|" + erpCode + "|" + rowNo;

                        //                //iCVQuantity 账面数量， iCVNum 账面辅计量数量（件数）， iCVCNum 盘点辅计量数量 ，iCVCQuantity 盘点数量（实盘数） 
                        //                sb.Append("insert into CheckVouchs(cCVCode,cInvCode,iCVNum,iCVQuantity,iCVCNum,iCVCQuantity,cFree1,");
                        //                sb.Append("cPosition,autoID,ID,iAdInQuantity,iAdInNum,iAdOutQuantity,iAdOutNum,cFree3,");
                        //                sb.Append("irowno,cbsysbarcode,cbufts) ");
                        //                sb.Append("values('" + erpCode + "','" + s["proCode"] + "',0,"+ uStrock + ",'" + s["barCount"].ToString());
                        //                sb.Append("','" + sp + "','" + s["color"] + "','" + erpPosition + "','" + autoID + "','" + ID);
                        //                sb.Append("',0,0,0,0,'" + s["trademark"] + "','" + rowNo + "','" + cbsysbarcode);
                        //                sb.Append("',DEFAULT)");
                        //            }


                        //        }

                        //        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        //        {
                        //            U8List.Add(sb.ToString());
                        //        }

                        //    }

                        //}
                        #endregion

                        #region 盘亏
                        //if (pk.Length > 0)
                        //{
                        //    foreach (var s in pk)
                        //    {
                        //        sb.Clear();
                        //        uStrock = 0; fStrock = 0; sp = 0;
                        //        uRows = psTable.Select("cInvCode = '" + s["proCode"] + "' and cFree1 = '" + s["color"] + "' and cFree3 = '" + s["trademark"] + "'");
                        //        rows = barTable.Select("proCode = '" + s["proCode"] + "' and color = '" + s["color"] + "' and trademark = '" + s["trademark"] + "'");
                        //        if (uRows.Length > 0)
                        //        {
                        //            uStrock = double.Parse(uRows[0]["iQuantity"].ToString());
                        //        }
                        //        if (rows.Length > 0)
                        //        {
                        //            fStrock = double.Parse(rows[0]["number"].ToString());
                        //        }
                        //        if (uStrock != fStrock)
                        //        {
                        //            sp = uStrock - double.Parse(s["number"].ToString()); //实盘数

                        //            //根据存货、颜色、商标查询盘点单是否有这一行
                        //            //有就修改实盘数  没有就新增一行
                        //            var pdRow = cvtable.Select("cInvCode = '" + s["proCode"] + "' and cFree1 = '" + s["color"] + "' and cFree3 = '" + s["trademark"] + "'");
                        //            if (pdRow.Length > 0)
                        //            {
                        //                sb.Append("update CheckVouchs set iCVCQuantity ='" + sp + "'");
                        //                sb.Append(",iCVCNum ='" + s["barCount"].ToString() + "' where autoID='" + pdRow[0]["autoID"] + "'");
                        //            }
                        //            else
                        //            {
                        //                change = true;
                        //                autoID += 1;
                        //                iChildId += 1;
                        //                rowNo += 1;
                        //                var cbsysbarcode = "||st18|" + erpCode + "|" + rowNo;

                        //                //iCVQuantity 账面数量， iCVNum 账面辅计量数量（件数）， iCVCNum 盘点辅计量数量 ，iCVCQuantity 盘点数量（实盘数） 
                        //                sb.Append("insert into CheckVouchs(cCVCode,cInvCode,iCVNum,iCVQuantity,iCVCNum,iCVCQuantity,cFree1,");
                        //                sb.Append("cPosition,autoID,ID,iAdInQuantity,iAdInNum,iAdOutQuantity,iAdOutNum,cFree3,");
                        //                sb.Append("irowno,cbsysbarcode,cbufts) ");
                        //                sb.Append("values('" + erpCode + "','" + s["proCode"] + "',0,"+ uStrock + ",'" + s["barCount"].ToString());
                        //                sb.Append("','" + sp + "','" + s["color"] + "','" + erpPosition + "','" + autoID + "','" + ID);
                        //                sb.Append("',0,0,0,0,'" + s["trademark"] + "','" + rowNo + "','" + cbsysbarcode);
                        //                sb.Append("',DEFAULT)");
                        //            }


                        //        }

                        //        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        //        {
                        //            U8List.Add(sb.ToString());
                        //        }
                        //    }

                        //}
                        #endregion
                        #endregion

                    }
                    #endregion

                    #region 如果在U8有新增行，需要修改id记录表数值
                    if (change)
                    {
                        sb.Clear();
                        sb.Append("update UFSystem.dbo.UA_Identity set iChildId='" + iChildId + "' where cVouchType='ch' and cAcc_Id='" + userLogin.UserInfo().baseCode + "'");
                        U8List.Add(sb.ToString());
                    }
                    #endregion

                    #endregion

                    #region 以U8盘点单子表为准(货位存货盘点时 只看盘点的存货)，查找物控应盘列表，如果U8有物控没有，则修改调整出库数
                    //var newTable = spTable.Clone();
                    foreach (DataRow dr in cvtable.Rows)
                    {
                        if ( (chType == "pc-pospro" && erpProCodes.Contains(dr["cInvCode"].ToString())) || (chType != "pc-pospro") )
                        {
                            sb.Clear();
                            var row = spTable.Select("proCode='" + dr["cInvCode"] + "' and color='" + dr["cFree1"] +
                                "' and trademark='" + dr["cFree3"] + "'");
                            if (row.Length <= 0)
                            {
                                //U8有 物控没有   直接修改盘点数和盘点件数
                                sb.Append("update CheckVouchs set iCVCQuantity ='0',iCVCNum ='0' where autoID='" + dr["autoID"] + "'");
                                U8List.Add(sb.ToString());
                            }
                        }

                    }
                    #endregion

                    #region 设置盘点报告同步状态
                    sb.Clear();
                    sb.Append("update pCh_CheckTask_report set isSync='1' where pchCode in('" + code + "')");
                    sqlList.Add(sb.ToString());
                    #endregion

                    #region 输出日志
                    txt.AddLogMsg("盘点单同步："+code);
                    foreach (var s in U8List)
                    {
                        txt.AddLogMsg(s);
                    }
                    #endregion

                    if (U8List.Count > 0)
                    {
                        rsl = cu_helper.TransUpdate(U8List, null, userLogin.UserInfo().baseCode);
                        if (rsl.Result)
                            rsl = cmd.MoreUpdate(sqlList);
                    }
                    else
                        rsl = cmd.MoreUpdate(sqlList);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //查询U8货位现存量
        public DataTable getPosSum(string posCode, ref string errMsg)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from InvPositionSum ");
                if (!string.IsNullOrWhiteSpace(posCode))
                {
                    sb.Append("where cPosCode = '" + posCode + "'");
                }
                var table = cu_helper.getData(sb.ToString(), userLogin.UserInfo().baseCode);//U8货位存量
                return table;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }
        
        //查询物控货位现存量
        public DataTable getBarPosSum(string posCode, ref string errMsg)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select b.warePosition,s.proCode,color,trademark,s.number from bar_ProductBarCode_Sub_info s ");
                sb.Append("left join bar_ProductBarCode_info b on b.barCode = s.barCode where b.barStatus = 'need-out' ");
                if (!string.IsNullOrWhiteSpace(posCode))
                {
                    sb.Append("and warePosition = '" + posCode + "' ");
                }
                var table = cmd.GetDataTable(sb.ToString()); //物控货位存量
                return table;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }

        //获取实盘存货信息
        public DataTable getSPPros(string pchCode,ref string errMsg)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select erpCode,s.proCode,s.color,trademark,sum(CONVERT(decimal(18,2),s.number)) number,count(*) barCount  ");
                sb.Append("from pCh_CheckTask_records sp inner join pCh_CheckTask_info t on t.pchCode=sp.pchCode ");
                sb.Append("inner join V_BarCode_Info b on b.barCode=sp.barCode inner join bar_ProductBarCode_Sub_info s ");
                sb.Append("on s.barCode = b.barCode ");
                if (!string.IsNullOrWhiteSpace(pchCode))
                {
                    sb.Append("where sp.pchCode='" + pchCode + "'");
                }
                sb.Append(" group by erpCode,s.proCode,s.color,trademark ");
               
                var table = cmd.GetDataTable(sb.ToString()); //实盘列表
                return table;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }

        
    }
}
